// stores/window.ts
export interface Window {
  id: string;
  appKey: string;
  title: string;
  icon: string;
  zIndex: number;
  path?: string;
  minimized: boolean;
  maximized: boolean;
  x: number;
  y: number;
  width: number;
  height: number;
  minWidth: number;
  minHeight: number;
  vm: any;
}

export const useWindowStore = (() => {
  const defaultZIndex = 1;
  const s = reactive({
    windows: useSessionStorage("active_window", [] as Window[]),
    userHabits: useLocalStorage("user_habits", {}),
    activeNum: 0, //活跃的窗口数量
    aliveNum: 0, //存活的窗口数量
    nextZIndex: useLocalStorage("window_app_nextZIndex", defaultZIndex),
    createWindow(app: any) {
      let habits = s.userHabits[app.key] ?? {};
      const x = habits.x ?? Math.random() * 200 + 100;
      const y = habits.y ?? Math.random() * 200 + 100;
      const width = habits.width ?? app.minWidth;
      const height = habits.height ?? app.minHeight;
      if (!habits) {
        habits = s.userHabits[app.key] = { width, height, x, y };
      }
      s.windows.push({
        x,
        y,
        id: new Date().toString(),
        appKey: app.key,
        title: app.name,
        icon: app.icon,
        zIndex: s.nextZIndex,
        path: app.path,
        minimized: false,
        maximized: false,
        minWidth: app.minWidth,
        minHeight: app.minHeight,
        width,
        height,
        vm: app.vm,
      });
      s.activeNum++;
      s.aliveNum++;
      s.nextZIndex++;
    },

    saveHabits: (app: Window) => {
      s.userHabits[app.appKey] = {
        x: app.x,
        y: app.y,
        width: app.width,
        height: app.height,
      };
    },
    closeWindow(windowId: string) {
      s.windows = s.windows.filter((s) => s.id !== windowId);
      s.activeNum--;
      s.aliveNum--;
      //如果没有活跃窗口了则重置nextZIndex
      if (!s.aliveNum) {
        s.nextZIndex = defaultZIndex;
      }
    },

    focusWindow(windowId: string) {
      const window = s.windows.find((s) => s.id === windowId);
      if (!window) return;
      window.zIndex = s.nextZIndex++;
      window.minimized = false;
    },

    minimizeWindow(windowId: string) {
      const window = s.windows.find((s) => s.id === windowId);
      if (!window) return;
      s.activeNum--;
      //如果没有活跃窗口了则重置nextZIndex
      if (!s.activeNum) {
        s.nextZIndex = defaultZIndex;
      }
      window.minimized = true;
      window.zIndex = defaultZIndex;
    },
  });
  return s;
})();
